﻿using System;
using UnityEditor;
using UnityEngine;
using ZyGame;
using UnityEngine.UI;
using ZyGame.Editor;

namespace ZyGame.Editor.UIBind
{
    class UICreateWindow : EditorWindow
    {
        public UIToolbarView ToolbarView;
        public UIPreviewView PreviewView;
        public UISettingView SettingView;
        public UIInspectorView InspectorView;
        public PSBLayerView LayerView;

        private void OnEnable()
        {
            ToolbarView = new UIToolbarView(this);
            LayerView = new PSBLayerView(this);
            SettingView = new UISettingView(this);
            InspectorView = new UIInspectorView(this);
            PreviewView = new UIPreviewView(this);
        }

        private void OnGUI()
        {
            ToolbarView.OnGUI();
            GUILayout.BeginHorizontal();
            LayerView.OnGUI();
            GUILayout.BeginVertical();
            switch (ToolbarView.view)
            {
                case ViewState.Editor:
                    PreviewView.OnGUI();
                    break;
                case ViewState.Setting:
                    SettingView.OnGUI();
                    break;
            }

            GUILayout.EndVertical();
            InspectorView.OnGUI();
            GUILayout.EndHorizontal();
        }
    }

    enum ViewState
    {
        Editor,
        Setting,
    }

    class UISettingView : SubWindow<UICreateWindow>
    {
        private SerializedObject serializedObject;

        public UISettingView(UICreateWindow createWindow) : base(createWindow)
        {
            serializedObject = new SerializedObject(UICustomSetting.instance);
        }

        public void OnGUI()
        {
            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(serializedObject.FindProperty("output"));
            EditorGUILayout.PropertyField(serializedObject.FindProperty("orgins"));

            if (EditorGUI.EndChangeCheck())
            {
                serializedObject.ApplyModifiedProperties();
                UICustomSetting.Save();
            }
        }
    }


    class UIToolbarView : SubWindow<UICreateWindow>
    {
        public ViewState view { get; private set; }

        public UIToolbarView(UICreateWindow createWindow) : base(createWindow)
        {
        }

        public void OnGUI()
        {
            GUILayout.BeginHorizontal(EditorStyles.toolbar);
            if (GUILayout.Button("File", EditorStyles.toolbarButton))
            {
                GenericMenu menu = new GenericMenu();
                menu.AddItem(new GUIContent("Open"), false, OpenFile);
                menu.AddItem(new GUIContent("Save"), false, SaveImportFile);
                menu.AddItem(new GUIContent("Save As"), false, SaveToOhterFile);
                menu.ShowAsContext();
            }

            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Setting", EditorStyles.toolbarButton))
            {
                if (view is ViewState.Editor)
                {
                    view = ViewState.Setting;
                }
                else if (view is ViewState.Setting)
                {
                    view = ViewState.Editor;
                }
            }

            if (GUILayout.Button("Export", EditorStyles.toolbarButton))
            {
            }

            GUILayout.EndHorizontal();
        }

        private void OpenFile()
        {
            string importPath = EditorPrefs.GetString("PSB_IMPORT_PATH", Application.dataPath);
            string filePath = EditorUtility.OpenFilePanel("选择导入文件", importPath, "psb,psd");
            if (filePath.IsNullOrEmpty())
            {
                return;
            }

            EditorPrefs.SetString("PSB_IMPORT_PATH", filePath);
            PSBImport.instance.Load(filePath);
        }

        public void SaveImportFile()
        {
        }

        public void SaveToOhterFile()
        {
        }
    }

    class UIPreviewView : SubWindow<UICreateWindow>
    {
        public UIPreviewView(UICreateWindow createWindow) : base(createWindow)
        {
        }

        public void OnGUI()
        {
            if (PSBImport.instance.layers is null || PSBImport.instance.layers.Length is 0)
            {
                return;
            }
        }
    }

    class UIInspectorView : SubWindow<UICreateWindow>
    {
        private Vector2 position;
        private Vector2 AnchorMin;
        private Vector2 AnchorMax;
        private Vector2 anchoredPosition;
        private Vector2 sizeDelta;
        private LayoutWindow2 _mWindow;
        private const float kDottedLineSize = 5f;
        private static float kDropdownSize = 49;

        public UIInspectorView(UICreateWindow createWindow) : base(createWindow)
        {
        }

        public void OnGUI()
        {
            if (PSBImport.instance.selection is null)
            {
                return;
            }

            position = GUILayout.BeginScrollView(position, GUILayout.Width(300));
            GUILayout.BeginVertical();
            LayerData current = PSBImport.instance.selection;
            GUILayout.BeginHorizontal();
            GUILayout.TextField(current.name);
            GUILayout.EndHorizontal();
            GUILayout.Label("Layout", EditorStyles.boldLabel);

            GUILayout.BeginHorizontal();
            Rect dropdownPosition = GUILayoutUtility.GetRect(0, 0);
            dropdownPosition.x += 2;
            dropdownPosition.y += 17;
            dropdownPosition.height = kDropdownSize;
            dropdownPosition.width = kDropdownSize;
            bool anyWithoutParent = current.parent is not null;
            using (new EditorGUI.DisabledScope(anyWithoutParent))
            {
                if (EditorGUI.DropdownButton(dropdownPosition, GUIContent.none, FocusType.Passive, "label"))
                {
                    GUIUtility.keyboardControl = 0;
                    _mWindow = new LayoutWindow2(PSBImport.instance.selection, parent);
                    PopupWindow.Show(dropdownPosition, _mWindow);
                }
            }

            if (!anyWithoutParent)
            {
                LayoutWindow2.DrawLayoutMode(new RectOffset(7, 7, 7, 7).Remove(dropdownPosition), current.anchorMin, current.anchorMax, current.anchoredPosition, current.sizeDelta);
                LayoutWindow2.DrawLayoutModeHeadersOutsideRect(dropdownPosition, current.anchorMin, current.anchorMax, current.anchoredPosition, current.sizeDelta);
            }
            GUILayout.BeginVertical();
            EditorGUILayout.Vector3Field(new GUIContent(""), current.anchoredPosition);
            EditorGUILayout.Vector2Field(new GUIContent(""), current.sizeDelta);
            GUILayout.EndVertical();
            GUILayout.EndHorizontal();


            GUILayout.EndVertical();
            GUILayout.EndScrollView();
        }
    }

    class PSBLayerView : SubWindow<UICreateWindow>
    {
        private Vector2 position;
        private float width = 300;

        public PSBLayerView(UICreateWindow createWindow) : base(createWindow)
        {
        }

        public void OnGUI()
        {
            if (PSBImport.instance.layers is null || PSBImport.instance.layers.Length is 0)
            {
                return;
            }

            position = GUILayout.BeginScrollView(position, GUILayout.Width(width));
            GUILayout.BeginVertical();
            for (int i = 0; i < PSBImport.instance.layers.Length; i++)
            {
                ShowLayer(PSBImport.instance.layers[i]);
            }

            GUILayout.EndVertical();
            GUILayout.EndScrollView();
        }

        private void ShowLayer(LayerData layerData)
        {
            Rect rect = EditorGUILayout.BeginHorizontal(
                layerData.selection ? EditorStyles.selectionRect : GUIStyle.none
            );
            if (layerData.isGroup)
            {
                Texture texture = EditorGUIUtility.IconContent("Folder Icon").image;
                layerData.foldout = EditorGUILayout.Foldout(layerData.foldout, "");
                GUILayout.Space(-40);
                GUILayout.Label(texture, GUILayout.Width(20), GUILayout.Height(20));
                GUILayout.Label(layerData.name, GUILayout.Width(150), GUILayout.Height(20));
            }
            else
            {
                if (layerData.texture is null)
                {
                    Texture texture = EditorGUIUtility.IconContent("GUIText Icon").image;
                    GUILayout.Label(texture, GUILayout.Width(20), GUILayout.Height(20));
                    GUILayout.Label(layerData.text, GUILayout.Width(170), GUILayout.Height(20));
                }
                else
                {
                    GUILayout.Label(layerData.texture, GUILayout.Width(20), GUILayout.Height(20));
                    GUILayout.Label(layerData.name, GUILayout.Width(170), GUILayout.Height(20));
                }
            }

            if (UnityEngine.Event.current.type == EventType.MouseDown && rect.Contains(UnityEngine.Event.current.mousePosition))
            {
                if (PSBImport.instance.selection is not null)
                {
                    PSBImport.instance.selection.selection = false;
                }

                layerData.selection = true;
                PSBImport.instance.selection = layerData;
                EditorWindow.focusedWindow.Repaint();
            }

            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            if (layerData.foldout is false)
            {
                return;
            }

            for (int i = 0; i < layerData.child.Count; i++)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Space(20);
                GUILayout.BeginVertical();
                ShowLayer(layerData.child[i]);
                GUILayout.EndVertical();
                GUILayout.EndHorizontal();
            }
        }
    }
}